<?php

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: text/html; charset=utf-8');

require 'facebook/facebook.php';

$facebook = new Facebook(array(
  'appId'  => '202355239779232',
  'secret' => 'aef66e0360c9aefe692b7fe054f9c80a',
));

$user = $facebook->getUser();

if ($user) {
	try {
		$user_profile = $facebook->api('/me');
	} catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
}

if (!$user) {
	$loginUrl = $facebook->getLoginUrl();
	echo '<!DOCTYPE html>', "\n";
	echo '<html>', "\n";
	echo '<head>', "\n";
	echo '<title>Arena Blitz</title>', "\n";
	echo '<meta name="viewport" content="width=308, initial-scale=1.0, minimum-scale=0.25, maximum-scale=4.0" />', "\n";
	echo '</head>', "\n";
	echo '<body style="background:url(Splash_background.png)">', "\n";
	echo '<a href="' . $loginUrl . '"><img src="Splash.png" width="266" height="180" alt="Login" title="Login"/></a>';
	echo '</body>', "\n";
	echo '</html>', "\n";
	return;
}

$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$browser = '';
if (stripos($user_agent, 'android') !== false) {
	$browser = 'Android';
} else if (stripos($user_agent, 'iphone') !== false) {
	$browser = 'iPhone';
} else if (stripos($user_agent, 'ipad') !== false) {
	$browser = 'iPad';
} else {
	$browser = 'Other';
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Arena Blitz</title>
<?php

$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$browser = '';

if (stripos($user_agent, 'android') !== false) {
	$browser = 'Android';
	echo '<meta name="viewport" content="width=573, initial-scale=1.0, minimum-scale=0.25, maximum-scale=4.0" />', "\n";
	
} else if (stripos($user_agent, 'iphone') !== false) {
	$browser = 'iPhone';
	echo '<meta name="viewport" content="width=640, initial-scale=0.5, target-densitydpi=160" />', "\n";
	
} else if (stripos($user_agent, 'ipad') !== false) {
	$browser = 'iPad';
	
} else {
	$browser = 'Other';
}

?>
<style type="text/css">
	html { width:100%; height:100%; margin:0; padding:0; }
	body { width:100%; height:100%; margin:0; padding:0; background:url(Splash_background.png); }
	#profile { position:absolute; top:0px; left:0px; width:100%; height:50px; background:white; overflow:hidden; }
	#map_area { position:absolute; top:50px; left:0px; width:573px; height:1257px; margin:0; padding:0; overflow:hidden; }
	#map_viewport { position:absolute; top:0px; left:0px; margin:0; padding:0; }
	#map_image { position:absolute; top:0px; left:0px; width:573px; height:1257px; }
	.player { position:absolute; top:0px; left:0px; width:32px; height:32px; background:#ff00ff; border:2px solid #ffff00; }
	#debug { position:absolute; top:1307px; left:0px; width:573px; height:20px; background:white; overflow:hidden; }
	#image { float:left; padding:0; margin:0; border:0; width:48px; height:48px; }
	#name { float:left; padding:10px; color:#ff00ff; font-weight:bold; }
	#quest_image { position:absolute; top:0px; left:0px; width:128px; height:96px; display:none; }
</style>
<script type="text/javascript">

var myFacebookId = '<?= htmlentities($user) ?>';
var latitude = 0;
var longitude = 0;
var count = 0;
var wpid = 0;
var fbuser = 0;
var viewport = null;
var first = true;

window.onload = function() {
	viewport = document.getElementById('map_viewport');
	window.setTimeout('getCoords()', 500);
	window.setInterval('submitUpdate()', 1000);
}

function getCoords() {
	if (navigator.geolocation)  {
		alert('Welcome to Arena Blitz!  Press OK to find your location.  Please be patient!');
		wpid = navigator.geolocation.watchPosition(geo_success, geo_error, {enableHighAccuracy:true, maximumAge:2000, timeout:20000});
	} else {
		alert("GPS not supported");
	}  
}
 
function geo_success(position) {
	var coords = position.coords;
	var point = convertPoint(latitude, longitude);
	var accuracy = position.coords.accuracy;
	
	count++;
	setDebug('[ ' + count + ' | ' + coords.latitude.toFixed(5) + ' | ' + coords.longitude.toFixed(5) + ' | ' + point.x.toFixed(1) + ' | ' + point.y.toFixed(1) + ' | ' + accuracy.toFixed(2) + ' ]');
	
	if (accuracy <= 50.0) {
		latitude = coords.latitude;
		longitude = coords.longitude;
	}

	if (first) {
		first = false;
		alert('You need gold.  Walk to the blue patch to snatch dubloons! (Yes, physically get up and walk)');
	}
}

function geo_error(error) {
	switch(error.code) {
		case error.TIMEOUT:
			alert ('Timeout');
			break;
		case error.POSITION_UNAVAILABLE:
			alert ('Position unavailable');
			break;
		case error.PERMISSION_DENIED:
			alert ('Permission denied');
			break;
		case error.UNKNOWN_ERROR:
			alert ('Unknown error');
			break;
	}
}

function createRequestObject() {
    var result = null;
    
    if (window.XMLHttpRequest) { 
        // Mozilla, Safari would use this method ...
        result = new XMLHttpRequest();
    } else if (window.ActiveXObject) { 
        // IE would use this method ...
        result = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    return result;
}

function submitUpdate() {
	if (latitude < 37.770 || latitude > 37.774) {
		return;
	}

	if (longitude < -122.406 || longitude > -122.402) {
		return;
	}

	var url = 'server.php?lat=' + latitude.toFixed(8) + '&long=' + longitude.toFixed(8);
	var http = createRequestObject();
    http.open('GET', url);
    http.onreadystatechange = function() {
		if (http.readyState == 4) {
			var response = http.responseText;
			parseResponse(response);
		}
	};
    http.send(null);
}


function convertPoint(latitude, longitude) {
	// Step 1:  Convert to radians
	latitude = latitude / 360.0 * (2.0 * Math.PI);
	longitude = longitude / 360.0 * (2.0 * Math.PI);
	
	// Step 2:  Convert to Mercator
	var x2 = longitude;
	var y2 = Math.log((Math.sin(latitude) + 1.0) / Math.cos(latitude));// / Math.log(2.0);
	
	// Step 3:  Translate/scale into our (rough) pixel ranges
	var x3 = 20000000.0 * (x2 + 2.13638);
	var y3 = 20000000.0 * (y2 - 0.71293);

	// Step 4:  Rotate
	// x' = x cos f - y sin f
	// y' = y cos f + x sin f
	var rot = 48.0 / 360.0 * 2.0 * Math.PI;
	var x4 = x3 * Math.cos(rot) - y3 * Math.sin(rot);
	var y4 = y3 * Math.cos(rot) + x3 * Math.sin(rot);
	
	// Step 5:  Flip the y-axis
	var x5 = 60.0 + 1.5 * x4
	var y5 = 1366.0 - 1.5 * y4;
	
	var point = new Object();
	point.x = x5;
	point.y = y5;
	return point;
}

function parseResponse(json) {
	if (json == null || json.length == 0) {
		return;
	}
	try {
		var response = eval(json);
		if (response == null || !response.length) {
			setDebug('empty response');
			return;
		}
		
		if (response[0].players) {
			updatePlayers(response[0].players);
		}
		
		if (response[0].quest) {
			updateQuest(response[0].quest);
		} else {
			hideQuest();
		}
		
		if (response[0].message) {
			alert(response[0].message);
		}
		
	} catch (ex) {
		setDebug('parseResponse: ' + ex.message);
	}
}


function updatePlayers(players) {
	for (var i = 0; i < players.length; i++) {
		updatePlayer(players[i].facebook_id, players[i].latitude, players[i].longitude);
	}
}

function updatePlayer(facebook_id, latitude, longitude) {
	var id = 'player_' + facebook_id;
	var el = document.getElementById(id);
	if (!el) {
		el = document.createElement('div');
		el.id = id;
		el.className = 'player';
		el.innerHTML = '<img id="image" src="https://graph.facebook.com/' + facebook_id + '/picture" width="32" height="32" style="width:32px; height:32px;"/>';
		if (facebook_id == myFacebookId) {
			el.style.zIndex = 100;
		}
		viewport.appendChild(el);
	}
	var point = convertPoint(latitude, longitude);
	el.style.left = (point.x - 16) + 'px';
	el.style.top = (point.y - 16) + 'px';
}

function updateQuest(quest) {
	var el = document.getElementById('quest_image');
	var point = convertPoint(quest.latitude, quest.longitude);
	el.style.left = (point.x - 64) + 'px';
	el.style.top = (point.y - 48) + 'px';
	el.style.display = 'block';
}

function hideQuest() {
	var el = document.getElementById('quest_image');
	el.style.display = 'none';
}

function setDebug(text) {
	document.getElementById('debug').innerHTML = text + '<br/>';
}
	
</script>
</head>
<body>

<div id="profile">
<img id="image" src="https://graph.facebook.com/<?php echo $user; ?>/picture" width="48" height="48"/>
<?= htmlentities($user_profile['name']) ?> &nbsp;|&nbsp;
<?= htmlentities($browser) ?> &nbsp;|&nbsp;
<a href="leaderboard.php">Leaders</a> &nbsp;|&nbsp;
<a href="<?= $facebook->getLogoutUrl() ?>">Logout</a>
</div>

<div id="map_area">
<div id="map_viewport">
<img id="map_image" src="background.png" width="428" height="1314"/>
<img id="quest_image" src="quest.png" width="128" height="96"/>
</div>
</div>

<div id="debug"></div>

</body>
</html>
